<template>

	<div>
		<div class="displayFlexBet bgfff mb10 pt10">
			<el-empty v-if="dataList3.length == 0" style="margin: 0 auto;" />
			<div v-else style="flex: 1;">
				<div style="padding: 10px 10px 0;">
					<el-date-picker type="year" v-model="year" @change="getEntAuxiliaryMaterialList" :clearable="false"
						format="yyyy" value-format="yyyy"></el-date-picker>
				</div>
				<div id="chart1" style="height: 250px;"></div>
			</div>
		</div>

		<!-- <el-tabs v-model="activeName" @tab-click="handleClick" type="card" style="background: #fff;position: relative;"> -->

		<div class="displayFlex bgfff mb10" style="padding:20px;border-radius: 8px;">
			<div v-for="(item,index) in materialList" :key="index" class="mr20 point" @click="chooseMaterial(item)"
				:style="{'color':materialId == item.id?'#3A3EF4':'#333'}">
				{{item.materialName}}
			</div>
		</div>

		<div class="displayFlexBet bgfff mb10" style="padding:20px;border-radius: 8px;">
			<div style="flex:1">
				<div style="color:#333;font-size: 18px;margin-bottom: 30px">{{materialName}}</div>

				<div style="padding:0 20px">
					<div style="border:1px solid#E4E4E5;border-radius: 8px;" class="displayFlex mb20 pad20">
						<div class="ml10 mr20">
							<img src="@/assets/sIcon94.png" style="width:64px;height:64px" />
						</div>
						<div>
							<div style="color:#4A5267;font-size:15px" class="mb20">累计采购</div>
							<div style="color:#3C3C3C;font-size:18px">
								{{countList1[0]?countList1[0].purchaseQty+countList1[0].unitValue:0}}
							</div>
						</div>
					</div>

					<div style="border:1px solid#E4E4E5;border-radius: 8px;" class="displayFlex pad20">
						<div class="ml10 mr20">
							<img src="@/assets/sIcon95.png" style="width:64px;height:64px" />
						</div>
						<div>
							<div style="color:#4A5267;font-size:15px" class="mb20">累计使用</div>
							<div style="color:#3C3C3C;font-size:18px">
								{{countList2[0]?countList2[0].useQty+countList2[0].unitValue:0}}
							</div>
						</div>
					</div>
				</div>
			</div>

			<div id="chart2" style="flex: 2;height: 250px;"></div>
		</div>

		<div style="background: #fff;padding:10px;border-radius: 8px;">
			<div class="displayFlexBet mb10">
				<div class="displayFlex point">
					<div :style="{'color':activeName == 'first'?'#3A3EF4':'#333'}" @click="activeName = 'first'">药剂耗材采购
					</div>
					<div style="color: #EDECF1;" class="ml20 mr20">|</div>
					<div :style="{'color':activeName == 'second'?'#3A3EF4':'#333'}" @click="activeName = 'second'">
						药剂耗材使用</div>
				</div>

				<div @click="visible1 = true,form=$options.data().form" class="displayFlex point">
					<el-button icon="el-icon-plus" type="primary" size="mini" plain>新增采购记录</el-button>
				</div>
			</div>

			<div style="" v-show="activeName == 'first'">
				<el-table :data="dataList1" style="background: #fff;" size="mini" border stripe>
					<el-table-column type="index" width="50">
					</el-table-column>
					<el-table-column prop="materialName" label="药剂/耗材名称">
					</el-table-column>
					<el-table-column prop="purchaseQty" label="数量" width="100">
					</el-table-column>
					<el-table-column prop="unitValue" label="单位" width="100">
					</el-table-column>
					<el-table-column prop="orderFileName" label="采购合同" align="center" show-overflow-tooltip>
						<template slot-scope="scope">
							<el-tag v-if="scope.row.orderFileName" type="primary" class="point"
								@click="previewFile(fileViewUrl+scope.row.orderFileId)"
								size="mini">{{scope.row.orderFileName}}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="orderFileName" label="采购发票" align="center" show-overflow-tooltip>
						<template slot-scope="scope">
							<el-tag v-if="scope.row.invoiceFileName" type="primary" class="point"
								@click="previewFile(fileViewUrl+scope.row.invoiceFileId)"
								size="mini">{{scope.row.invoiceFileName}}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="deliveryFileName" label="发货单" align="center" show-overflow-tooltip>
						<template slot-scope="scope">
							<el-tag v-if="scope.row.deliveryFileName" type="primary" class="point"
								@click="previewFile(fileViewUrl+scope.row.deliveryFileId)"
								size="mini">{{scope.row.deliveryFileName}}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="inStorageTime" label="录入时间" width="120">
						<template slot-scope="scope">
							<div>{{scope.row.inStorageTime.split(" ")[0]}}</div>
						</template>
					</el-table-column>
					<el-table-column prop="userName" label="台账录入" width="100">
					</el-table-column>
					<el-table-column label="操作" width="100" align="center">
						<template slot-scope="scope">
							<el-button type="text" size="small" @click="visible1 = true,form = scope.row">编辑</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div class="displayFlexBet mt10">
					<el-pagination @current-change="get()" :current-page.sync="getParams2.pageIndex"
						:page-size="getParams2.pageSize" layout="total, prev, pager, next" :total="getParams2.total">
					</el-pagination>
				</div>
			</div>

			<div style="background: #fff;padding: 0 10px 10px;" v-show="activeName == 'second'">
				<el-table :data="dataList2" style="background: #fff;" size="mini" border stripe>
					<el-table-column type="index" width="50">
					</el-table-column>
					<el-table-column prop="materialName" label="药剂/耗材名称">
					</el-table-column>
					<el-table-column prop="useQty" label="用量" width="100">
					</el-table-column>
					<el-table-column prop="unitValue" label="单位" width="100">
					</el-table-column>
					<el-table-column prop="useTime" label="录入时间">
						<template slot-scope="scope">
							<div v-if="scope.row.useTime">{{scope.row.useTime.split(" ")[0]}}</div>
						</template>
					</el-table-column>
					<el-table-column prop="userName" label="台账录入">
					</el-table-column>
				</el-table>
				<div class="displayFlexBet mt10">
					<el-pagination @current-change="getPageUse()" :current-page.sync="getParams3.pageIndex"
						:page-size="getParams3.pageSize" layout="total, prev, pager, next" :total="getParams3.total">
					</el-pagination>
				</div>
			</div>
		</div>

		<el-dialog :visible.sync="visible1" title="药剂/耗材信息" width="450px">
			<el-form ref="form" :model="form" :rules="formRules" label-width="120px">
				<el-form-item label="药剂/耗材名称" prop="materialName">
					<el-select v-model="form.materialId" placeholder="请选择" filterable style="width: 100%;"
						@change="changeMater">
						<el-option v-for="item in materialList" :key="item.id" :label="item.materialName"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="采购量" prop="purchaseQty">
					<div class="displayFlexBet">
						<el-input v-model="form.purchaseQty" style="width: 250px;"></el-input>
						<div>{{unitVlaue}}</div>
					</div>
				</el-form-item>

				<el-form-item label="采购合同" prop="orderFileId">
					<div>
						<el-upload accept=".pdf" :limit="1" :multiple="false" :file-list="form.orderFileList" action="#"
							:auto-upload="false" :on-change="changeorderFile" :on-remove="removeorderFile">
							<el-button type="text" style="margin: 0 0 -15px 0">采购合同</el-button>
							<span style="font-size: 10px;color: #999;">(仅支持pdf文件)</span>
						</el-upload>
					</div>
				</el-form-item>

				<el-form-item label="采购发票" prop="invoiceFileId">
					<div>
						<el-upload accept=".pdf" :limit="1" :multiple="false" :file-list="form.invoiceFileList"
							action="#" :auto-upload="false" :on-change="changeinvoiceFile"
							:on-remove="removeinvoiceFile">
							<el-button type="text" style="margin: 0 0 -15px 0">采购发票</el-button>
							<span style="font-size: 10px;color: #999;">(仅支持pdf文件)</span>
						</el-upload>
					</div>
				</el-form-item>

				<el-form-item label="发货单" prop="deliveryFileId">
					<div>
						<el-upload accept=".pdf" :limit="1" :multiple="false" :file-list="form.deliveryFileList"
							action="#" :auto-upload="false" :on-change="changedeliveryFile"
							:on-remove="removedeliveryFile">
							<el-button type="text" style="margin: 0 0 -15px 0">发货单</el-button>
							<span style="font-size: 10px;color: #999;">(仅支持pdf文件)</span>
						</el-upload>
					</div>
				</el-form-item>

				<el-form-item label="入库时间" prop="inStorageTime">
					<el-date-picker v-model="form.inStorageTime" type="date" placeholder="入库时间"
						value-format="yyyy-MM-dd" format="yyyy-MM-dd">
					</el-date-picker>
				</el-form-item>


				<el-form-item style="text-align: center;margin-left: -90px!important;">
					<el-button type="primary" @click="saveOrUpdate">保存</el-button>
					<el-button @click="cancle">取消</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<!--文件预览-->
		<el-dialog :visible.sync="getParams4.visible1" width="800px" :title="'文件预览'">
			<div id="content" v-if="getParams4.pdfUrl">
				<pdf ref="pdf" :src="getParams4.pdfUrl" v-for="(page,index) in getParams4.numPages" :page="page" />
			</div>
		</el-dialog>

	</div>

</template>

<script>
	import moment from 'moment'
	import $ from 'jquery'
	let that
	let APPKEY = '5da5441f62e48aedc7a3853ffc75c2db';
	let PRODID = 'gf';
	let UPLOAD_ACTION = '/upload';
	let VIEW_ACTION = '/view';
	let REMOVE_ACTION = '/remove';
	let IMGURL = 'https://www.weifeibangbang.com/wfbb-webupload/service/sys/file/upload';
	import {
		Session
	} from '@/utils/storage';
	import pdf from 'vue-pdf'
	import * as echarts from 'echarts';

	export default {
		components: {
			pdf
		},
		data() {
			return {
				fileViewUrl: this.baseURL + 'file/download?fileId=',
				visible1: false,
				contentHeight: window.innerHeight,
				activeName: "first",
				materialList: [],
				unitList: [],
				year: moment().format('YYYY'),
				getParams: {
					busiStatus: "IN_USE"
				},
				getParams4: {
					visible1: false,
					numPages: 1,
					pdfUrl: ''
				},
				unitVlaue: "吨",
				form: {
					id: '', // 药剂id
					materialName: '', // 药剂名称，必填
					unitCode: '', // 药剂单位，必填
					orderFileList: [],
					orderFile: '',
					orderFileId: '',
					invoiceFileList: [],
					invoiceFile: '',
					invoiceFileId: '',
					deliveryFileList: [],
					deliveryFile: '',
					deliveryFileId: '',
					unitVlaue: '',
					inStorageTime: moment().format('YYYY-MM-DD')
				},
				formRules: {
					materialName: [{
						required: true,
						message: '请输入药剂/耗材名称',
						trigger: 'blur',
					}],
					unitCode: [{
						required: true,
						message: '请输入药剂/耗材单位',
						trigger: 'blur'
					}]
				},
				dataList1: [],
				dataList2: [],
				dataList3: [],
				countList1: [],
				countList2: [],
				materialList: [],
				materialId: '',
				materialName: '',
				getParams2: {
					pageIndex: 1,
					pageSize: 20,
					total: 0,
				},
				getParams3: {
					pageIndex: 1,
					pageSize: 20,
					total: 0,
				},
			}
		},
		created: function() {},
		mounted: function() {
			that = this

			that.ajax({
				url: '/codeType/listCodeValue',
				data: {
					typeCode: 'UNIT_TYPE'
				},
				success: function(data) {
					if (data.status == 1) {
						that.unitList = data.data;
					}
				}
			});

			that.getEntAuxiliaryMaterialList()

		},

		methods: {

			previewFile(pdfUrl) {
				//console.log(pdfUrl)
				that.getParams4.visible1 = true
				// let loading = this.$loading({
				// 	target: "#content",
				// 	lock: true,
				// 	text: 'Loading',
				// 	spinner: 'el-icon-loading',
				// 	background: 'rgba(0, 0, 0, 0.7)'
				// });
				that.getParams4.pdfUrl = pdf.createLoadingTask(pdfUrl)
				that.getParams4.pdfUrl.promise.then(pdf => {
					//console.log(pdf)
					that.getParams4.numPages = pdf.numPages // 这里拿到当前pdf总页数
					//loading.close();
				})
			},

			getChart() {
				that.ajax({
					url: '/entAuxiliaryMaterial/purchase/getPurchaseCharts',
					data: JSON.stringify({
						year: that.year
						//materialId: that.materialId
					}),
					contentType: 'application/json',
					success: function(result) {
						that.dataList3 = result.data

						setTimeout(function() {
							let xAxisData = []
							let seriesData1 = []
							let seriesData2 = []
							let seriesData3 = []
							for (let item of result.data) {
								xAxisData.push(item.materialName)
								//seriesData1.push(item.purchaseQty)
								seriesData2.push(item.useQty)
								seriesData3.push(item.storageQty)
							}
							var chartDom = document.getElementById('chart1');
							var myChart = echarts.init(chartDom);
							var option;

							option = {
								tooltip: {
									trigger: 'axis',
									axisPointer: {
										type: 'shadow'
									}
								},
								legend: {
									x: 'right', // 可设定图例在左、右、居中
									y: 'top', // 可设定图例在上、下、居中
									left: 'right',
									orient: "vertical"
								},
								grid: {
									left: '3%',
									right: '4%',
									bottom: '3%',
									containLabel: true
								},
								xAxis: [{
									type: 'category',
									data: xAxisData,
									//show: false, // 不显示坐标轴线、坐标轴刻度线和坐标轴上的文字
									axisTick: {
										show: false // 不显示坐标轴刻度线
									},
									axisLine: {
										show: false, // 不显示坐标轴线
									},
									axisLabel: {
										show: true, // 不显示坐标轴上的文字
									},
									splitLine: {
										show: false // 不显示网格线
									}
								}],
								yAxis: [{
									type: 'value',
									//show: false, // 不显示坐标轴线、坐标轴刻度线和坐标轴上的文字
									axisTick: {
										show: false // 不显示坐标轴刻度线
									},
									axisLine: {
										show: false, // 不显示坐标轴线
									},
									axisLabel: {
										show: false, // 不显示坐标轴上的文字
									},
									splitLine: {
										show: false // 不显示网格线
									}
								}],
								series: [{
										name: '使用量',
										type: 'bar',
										stack: 'Ad',
										emphasis: {
											focus: 'series'
										},
										itemStyle: {
											// 设置柱状图颜色
											color: '#5255C6'
										},
										label: {
											show: true,
										},
										barWidth: '50',
										data: seriesData2
									},
									{
										name: '库存量',
										type: 'bar',
										stack: 'Ad',
										emphasis: {
											focus: 'series'
										},
										itemStyle: {
											// 设置柱状图颜色
											color: '#8DE5A8'
										},
										label: {
											show: true,
										},
										barWidth: '50',
										data: seriesData3
									}
								]
							};

							option && myChart.setOption(option);
						}, 500)


					},
				})

				that.ajax({
					url: '/entAuxiliaryMaterial/purchase/getMonthPurchaseList',
					data: JSON.stringify({
						materialId: that.materialId,
						year: that.year
					}),
					contentType: 'application/json',
					success: function(result) {
						let xAxisData = []
						let seriesData1 = []
						for (let item of result.data) {
							xAxisData.push(item.dateStr)
							seriesData1.push(item.qty || 0)
						}
						var chartDom = document.getElementById('chart2');
						var myChart = echarts.init(chartDom);
						var option;

						option = {
							tooltip: {
								trigger: 'axis',
								axisPointer: {
									type: 'shadow'
								}
							},
							legend: {},
							grid: {
								left: '3%',
								right: '4%',
								bottom: '3%',
								containLabel: true
							},
							xAxis: {
								type: 'category',
								data: xAxisData
							},
							yAxis: {
								type: 'value'
							},
							series: [{
								data: seriesData1,
								type: 'bar'
							}]
						};

						option && myChart.setOption(option);
					},
				})
			},

			handleClick() {

			},

			changeMater() {
				let thisIndex = that.materialList.findIndex(item => item.id == that.form.materialId)
				if (thisIndex != -1) {
					that.form.materialName = that.materialList[thisIndex].materialName
					that.unitVlaue = that.materialList[thisIndex].uniValue
				}
			},

			getPageUse() {
				that.ajax({
					url: '/entAuxiliaryMaterial/purchase/pageUse?ticketId=' + Session.get('token') +
						'&pageIndex=' + that.getParams3.pageIndex + '&pageSize=' + that.getParams3.pageSize,
					data: JSON.stringify({
						materialId: that.materialId,
						year: that.year
					}),
					contentType: 'application/json',
					success: function(result) {
						that.dataList2 = result.data.records
						that.getParams3.total = result.data.total
					},
				})

				that.ajax({
					url: '/entAuxiliaryMaterial/purchase/countUsed',
					data: JSON.stringify({
						materialId: that.materialId
					}),
					contentType: 'application/json',
					success: function(result) {
						that.countList2 = result.data
					},
				})
			},

			get() {
				that.ajax({
					url: '/entAuxiliaryMaterial/purchase/page?ticketId=' + Session.get('token') +
						'&pageIndex=' + that.getParams2.pageIndex + '&pageSize=' + that.getParams2.pageSize,
					data: JSON.stringify({
						materialId: that.materialId,
						year: that.year
					}),
					contentType: 'application/json',
					success: function(result) {
						that.dataList1 = result.data.records
						that.getParams2.total = result.data.total
					},
				})

				that.ajax({
					url: '/entAuxiliaryMaterial/purchase/countPurchase',
					data: JSON.stringify({
						materialId: that.materialId
					}),
					contentType: 'application/json',
					success: function(result) {
						that.countList1 = result.data
					},
				})
			},

			changedeliveryFile: function(file, fileList) {
				var _this = this;
				file.url = URL.createObjectURL(file.raw);
				// if (file.raw.type.indexOf("pdf") == -1) {
				// 	return this.$message({
				// 		message: '请上传pdf文件',
				// 		type: 'warning'
				// 	});
				// }
				_this.form.deliveryFileList = fileList
				_this.form.deliveryFile = file;
			},

			removedeliveryFile() {
				this.form.deliveryFileList = []
				this.form.deliveryFile = ''
			},

			changeinvoiceFile: function(file, fileList) {
				var _this = this;
				file.url = URL.createObjectURL(file.raw);
				// if (file.raw.type.indexOf("pdf") == -1) {
				// 	return this.$message({
				// 		message: '请上传pdf文件',
				// 		type: 'warning'
				// 	});
				// }
				_this.form.invoiceFileList = fileList
				_this.form.invoiceFile = file;
			},

			removeinvoiceFile() {
				this.form.invoiceFileList = []
				this.form.invoiceFile = ''
			},

			changeorderFile: function(file, fileList) {
				var _this = this;
				file.url = URL.createObjectURL(file.raw);
				// if (file.raw.type.indexOf("pdf") == -1) {
				// 	return this.$message({
				// 		message: '请上传pdf文件',
				// 		type: 'warning'
				// 	});
				// }
				_this.form.orderFileList = fileList
				_this.form.orderFile = file;
			},

			removeorderFile() {
				this.form.orderFileList = []
				this.form.orderFile = ''
			},

			updateBusiStatus(item) {
				this.$confirm('是否确定此操作?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.ajax({
						url: '/entAuxiliaryMaterial/updateBusiStatus',
						data: {
							materialId: item.id
						},
						contentType: 'application/x-www-form-urlencoded',
						success: function(result) {
							if (result.data) {
								that.getEntAuxiliaryMaterialList()
							}
						},
					})
				})
			},

			getEntAuxiliaryMaterialList() {
				that.getParams.year = that.year
				that.ajax({
					url: '/entAuxiliaryMaterial/getEntAuxiliaryMaterialList',
					data: JSON.stringify(that.getParams),
					contentType: 'application/json',
					success: function(result) {
						that.materialList = result.data
						if (!that.materialId && that.materialList.length > 0) {
							that.materialId = that.materialList[0].id
							that.materialName = that.materialList[0].materialName
						}

						that.get()
						that.getPageUse()
						that.getChart()
					},
				})
			},

			chooseMaterial(item) {
				that.materialId = item.id
				that.materialName = item.materialName
				that.get()
				that.getPageUse()
				that.getChart()
			},

			cancle() {
				that.form = that.$options.data().form
				that.visible1 = false
			},

			saveOrUpdate() {
				that.$refs['form'].validate(function(valid) {
					if (valid) {
						that.$confirm('是否确定保存, 是否继续?', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => {
							that.uploadFile(function(orderFileId) {
								that.uploadFile(function(invoiceFileId) {
									that.uploadFile(function(deliveryFileId) {
										that.form.orderFileId = orderFileId
										that.form.invoiceFileId = invoiceFileId
										that.form.deliveryFileId = deliveryFileId
										that.ajax({
											url: '/entAuxiliaryMaterial/purchase/save',
											data: JSON.stringify(that
												.form),
											contentType: 'application/json',
											success: function(result) {
												that.$message.success(
													"保存成功！")
												that.cancle()
												that.getEntAuxiliaryMaterialList()
											},
										})
									}, that.form.deliveryFile)
								}, that.form.invoiceFile)
							}, that.form.orderFile)
						})
					}
				})
			},

			randomChar: function(l) {
				var x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
				var tmp = "";
				var timestamp = new Date().getTime();
				for (var i = 0; i < l; i++) {
					tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
				}
				return timestamp + tmp;
			},

			uploadFile: function(callback, fileItem) {
				var _this = this;

				if (fileItem && fileItem.raw) {
					var formdata = new FormData()
					formdata.append("file", fileItem.raw);
					formdata.append("appKey", APPKEY);
					formdata.append("businessCode", that.randomChar(19));
					formdata.append("prodID", PRODID);
					$.ajax({
						url: 'https://www.weifeibangbang.com/wfbb-webupload/service/sys/file/upload/upload',
						data: formdata,
						type: 'POST',
						dataType: 'json',
						contentType: false,
						processData: false,
						success: function(result) {
							var fileId = result.message.fileID;
							callback(fileId);
						},
						error: function() {}
					})
				} else {
					callback('')
				}
			},

		}
	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>